<template>
  <div v-if="admin.isLogin" class="app">
    <Login></Login>
  </div>
  <template v-else>
    <div :class="heightHeader ? 'app heightHeader' : 'app'">
      <el-config-provider :locale="zhCn">
        <el-container>
          <el-header>
            <div class="header">
              <div style="display: flex; flex-grow: 1">
                <div :class="fullScreen ? 'mini-logo logo' : 'logo'">
                  <div class="logo-inside">
                    <h1 style="width: 190px; padding: 0 20px">BICIXI</h1>
                    <h1 style="width: 60px" @click="showAside = true">
                      <el-icon style="font-size: 1rem; margin-right: 12px">
                        <Menu />
                      </el-icon>B
                    </h1>
                  </div>
                </div>
                <div v-if="isTopHeader" ref="topMenu">
                  <headMenu :options="head" :activeIndex="headActive + ''" :has_child="false" @select="onSelectHead">
                  </headMenu>
                </div>
              </div>
              <div class="message" ref="message">
                <div v-loading="loading" style="width: 40px"></div>
                <!-- 菜单查询 -->
                <el-icon style="margin-right: 10px; cursor: pointer" @click="onOpenSearch"
                  color="var(--el-color-primary)">
                  <Search />
                </el-icon>
                <!-- <Transition>
                  <div v-if="searchwidth" class="search">
                    <el-autocomplete v-model="searchkey" :fetch-suggestions="onSearch" clearable class="inline-input"
                      :teleported="false" placeholder="菜单名称" @select="(e: any) => handleSelect(e)" />
                  </div>
                </Transition> -->
                <!-- 通知 -->
                <!-- <notification v-if="head" :head="head"></notification> -->
                <!-- 主题切换 -->
                <el-switch v-model="sIsDarkStore.isDark" @change="toggleTheme" active-color="#13ce66"
                  inactive-color="#ff4949"></el-switch>
                <!-- 头像菜单 -->
                <div class="avatar-menu" ref="avatarMenu">
                  <el-dropdown trigger="click" v-if="userInfo">
                    <span class="el-dropdown-link">
                      {{ userInfo.name || userInfo.username }}({{ userInfo.roles ? userInfo.roles[0].name : '用户' }})
                      <el-avatar :src="userInfo?.headImg || defaultAvatar" size="small"
                        class="avatar-image"></el-avatar>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="onRoutertoAccount">个人中心</el-dropdown-item>
                        <el-dropdown-item @click="onLogout">退出登录</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </div>
          </el-header>
          <el-container>
            <transition name="hide-aside">
              <el-aside v-if="!fullScreen" :class="collapse ? 'aside collapse' : 'aside'">
                <asideMenu :collapse="collapse" :options="isTopHeader ? aside : head" :activeIndex="asideActive + ''">
                </asideMenu>
                <div :class="collapse ? 'collapse-btn' : 'collapse-btn rotate'"
                  @click="sisCollapseStore.setCollapse(!collapse)">
                  <el-icon>
                    <ArrowRight />
                  </el-icon>
                </div>
              </el-aside>
            </transition>
            <el-main style="background: var(--el-bg-color-page); position: relative; scroll-behavior:smooth" id="main">
              <div class="main">
                <el-breadcrumb separator="/" style="margin-bottom: 0">
                  <template v-for="item in bread" :key="item.url">
                    <el-breadcrumb-item><span @click="onRoutertoBread(item)"
                        :class="item.type === MENUTYPE.目录 ? '' : 'breadcrumbblack'">
                        {{ item.name }}
                      </span></el-breadcrumb-item>
                  </template>
                </el-breadcrumb>
                <bFullScreen />
                <el-button @click="router.back()" v-if="menu?.type === MENUTYPE.按钮" type="primary"
                  style="margin: 5px; float: right">返回</el-button>
                <router-view />
              </div>
            </el-main>
          </el-container>
        </el-container>
        <el-drawer v-if="fullScreen" v-model="showAside" direction="ltr" :show-close="false" size="210px">
          <template #header>
            <h1>LOGO</h1>
          </template>
          <asideMenu :options="isTopHeader ? aside : head" :activeIndex="asideActive + ''">
          </asideMenu>
        </el-drawer>
      </el-config-provider>
    </div>
  </template>
</template>

<script setup lang="ts">
import headMenu from "./components/App/head_menu.vue";
import asideMenu from "./components/App/aside_menu.vue";
import notification from "./components/App/b_notification.vue";
import defaultAvatar from "./assets/OIP-C.jpg?url";
import Login from "./views/_login.vue";
import bFullScreen from "./components/widget/b_full_screen.vue";
import {
  ElButton,
  ElContainer,
  ElDrawer,
  ElAside,
  ElBreadcrumb,
  ElBreadcrumbItem,
  ElHeader,
  ElMain,
  ElSwitch,
  ElConfigProvider,
  ElIcon,
  ElAutocomplete,
  ElAvatar,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu
} from "element-plus";
import { Menu, Search, ArrowRight } from "@element-plus/icons-vue";
import { computed, nextTick, ref, useTemplateRef, watch } from "vue";
import { useRoute, useRouter, type RouteLocationNormalizedLoadedGeneric } from "vue-router";
import {
  fullScreenStore,
  adminStore,
  pagebuttonStore,
  loadingStore,
  headStore,
  isDarkStore,
  isCollapseStore,
} from "../store/index";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import { MENUTYPE } from "@b/model/enum";

const sFullScreenStore = fullScreenStore();
const spagebuttonStore = pagebuttonStore();
const sisCollapseStore = isCollapseStore();
const sIsDarkStore = isDarkStore();
const sheadStore = headStore();
const router = useRouter();
const route = useRoute()
const collapse = computed(() => sisCollapseStore.isCollapse);
const bread = computed(() => spagebuttonStore.bread);
const fullScreen = computed(() => sFullScreenStore.fullscreen);
const searchwidth = ref(0); //右上角菜单查询宽度（是否打开）
const searchkey = ref(""); //右上角菜单查询
const headActive = computed(() => spagebuttonStore.headActive); //当前头部导航
const asideActive = computed(() => spagebuttonStore.asideActive); //当前侧边导航
const menu = computed(() => spagebuttonStore.menuSelf); //当前导航
const aside = computed(() => sheadStore.asideOption); //当前侧边列表
const admin = adminStore(); //当前登录账号信息
const userInfo = computed(() => admin.userInfo); //当前登录账号信息
const sloadingStore = loadingStore(); //加载
const showAside = ref(false);
const loading = computed(() => sloadingStore.loading);
const heightHeader = ref(false);
const topMenu = useTemplateRef<HTMLElement>("topMenu");
const message = useTemplateRef<HTMLElement>("message");
const isTopHeader = ref(true);
const topMenuWidth = ref(0);
const head = computed(() => sheadStore.options); //当前头部列表

let timer: number = 0;
const getIsTopHeader = () => {
  //当头部空间不足时，头部菜单在侧边显示
  //头部菜单宽度加上logo宽度小于窗口宽度时，头部菜单并入侧边菜单
  const otherWidth = (fullScreen.value ? 60 : 190) + 40;
  isTopHeader.value = topMenuWidth.value + otherWidth < innerWidth;
  nextTick().then(() => {
    heightHeader.value =
      (topMenu.value?.offsetWidth || 0) +
      otherWidth +
      (message.value?.offsetWidth || 0) >
      innerWidth;
  });
};
admin.setuserInfo();
const getMemo = async () => {
  await sheadStore.getMemu('recache');
  topMenuWidth.value = topMenu.value?.offsetWidth || 0;
  getIsTopHeader();
}
sFullScreenStore.changefullScreen(false);
watch(() => admin.isLogin, async (val) => {
  if (val) return;
  await getMemo()
  getAside(route)
})
const promise = getMemo()
window.addEventListener("resize", (e: Event | { target: Window }) => {
  clearTimeout(timer);
  timer = setTimeout(() => {
    getIsTopHeader();
    const change = spagebuttonStore.headActive !== 0;
    sFullScreenStore.setWindowWidth((e as { target: Window }).target?.innerWidth, change);
  }, 100);
});
const getAside = async (val: RouteLocationNormalizedLoadedGeneric) => {
  const res = await spagebuttonStore.setRelationship(val.path);
  if (!res) router.replace("/403")
  await sheadStore.getAsideByPage(headActive.value, val.fullPath);
}
router.beforeEach(async (val) => {
  const notCheck = ["/403", "/404"];
  if (notCheck.includes(val.path) || admin.isLogin) return;
  await promise
  getAside(val)
});
const onSelectHead = async (id: string) => {
  const fristPage = await sheadStore.getAsideByHead(Number(id));
  if (fristPage) {
    router.push(fristPage);
  }
};
const onRoutertoBread = (item: interfaceMenu) => {
  if (item.type !== 1) {
    router.push(item.router)
  }
};
//右上角的菜单搜索功能
// const onSearch = (queryString: string, cb: (data: (interfaceMenu & { value: string })[]) => void) => {
//   const filter: (interfaceMenu & { value: string })[] = [];
//   if (queryString) {
//     if (!head.value || head.value.length == 0) return;
//     Utils.deepForeach(
//       head.value,
//       (value) => {
//         if (value.name.includes(queryString) && value.type === 2) {
//           filter.push({ ...value, value: value.name });
//         }
//       },
//       { child: "children" },
//     );
//   }
//   const results = filter;
//   cb(results);
// };
const handleSelect = (target: { url: string }) => {
  router.push(target.url);
};

const onOpenSearch = () => {
  searchwidth.value = searchwidth.value == 193 ? 0 : 193;
};

const toggleTheme = () => {
  sIsDarkStore.change();
};

const onLogout = () => {
  admin.logOut();
};

const onRoutertoAccount = () => {
  router.push("/account");
};
</script>

<style scoped>
.app {
  background: var(--el-bg-color);
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  margin-left: 10px;
  cursor: pointer;
}

.el-dropdown-link .avatar-image {
  margin-left: 10px;
}

.el-main {
  --el-main-padding: 0;
}

.header {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 100%;
  border-bottom: 1px solid var(--el-border-color);
  height: var(--header-height);
  transition: height 0.3s;
}

.el-header {
  height: 100%;
}

.el-header .message {
  display: flex;
  align-items: center;
  align-self: flex-end;
  flex-grow: 1;
}

.el-header .message .account {
  color: var(--el-color-primary);
  cursor: pointer;
  height: 100%;
  display: flex;
  align-items: center;
  white-space: nowrap;
  overflow: hidden;
}

.el-header .message img {
  border-radius: 50%;
  margin-right: 14px;
  width: 30px;
  height: 30px;
}

.el-aside {
  position: relative;
  height: calc(100vh - 60px);
  border-right: 1px solid var(--el-border-color);
  transition: width 0.3s;
  z-index: 99;
  background: var(--el-bg-color);
  --el-aside-width: 210px;
  overflow: unset;
}

.el-aside.collapse {
  --el-aside-width: calc(var(--el-menu-icon-width) + var(--el-menu-base-level-padding)* 2 + 2px);
}

.collapse-btn {
  position: absolute;
  bottom: 30px;
  right: -15px;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: var(--el-bg-color);
  transition: all 0.6s;
  border: 1px solid var(--el-border-color);
  border-radius: 50%;
}

.collapse-btn:hover {
  color: var(--el-color-primary);
}

.rotate {
  transform: rotate(180deg);
}

.modal {
  height: 100vh;
  position: fixed;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 98;
}

.account-list {
  text-align: center;
  padding: 8px 0;
}

.procure-id+.procure-id::before {
  content: " ,";
}

.el-breadcrumb {
  padding: 8px 30px;
  background-color: var(--el-bg-color);
  line-height: normal;
}

.flex.el-breadcrumb {
  padding: 12px 30px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.flex.el-breadcrumb>div {
  display: flex;
  align-items: center;
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  display: flex;
  padding: 4px 8px;
  line-height: normal;
}

.flex.el-breadcrumb>div>i {
  margin-left: 8px;
}

.flex.el-breadcrumb>div>i:hover {
  color: var(--el-color-primary-light-3);
}

.flex.el-breadcrumb> :nth-child(n) {
  margin-right: 14px;
  white-space: nowrap;
}

.flex.el-breadcrumb .activebaread {
  color: var(--el-color-primary);
}

.breadcrumbblack {
  font-weight: 600;
  color: var(--el-color-primary);
  cursor: pointer;
}

.showaside {
  display: none;
}

.search {
  width: 193px;
  margin-right: 10px;
}

.drawer-bottom {
  display: flex;
  align-items: center;
}

.drawer-bottom .el-input {
  width: 200px;
  margin-right: 12px;
}

.hide-aside-enter-active,
.hide-aside-leave-active {
  transition: all 0.5s ease;
}

.hide-aside-enter-from,
.hide-aside-leave-to {
  transform: translate(-210px, -100%) scale(0);
  width: 0;
}

.mini-logo .logo-inside {
  transform: translateX(-190px);
}

.logo-inside {
  transition: all 0.5s;
  transform: translateX(0);
  display: flex;
  width: calc(60px + 190px);
}

.logo {
  min-width: 190px;
  width: 190px;
  overflow: hidden;
  height: var(--el-header-height);
  line-height: var(--el-header-height);
  transition: width 0.5s;
}

.mini-logo.logo {
  min-width: 60px;
  width: 60px;
}

/** 右上角菜单搜索框打开关闭动画**/
.v-enter-active,
.v-leave-active {
  transition: width 0.5s ease;
  width: 192px;
}

.v-enter-from,
.v-leave-to {
  width: 0;
}

/** 左侧菜单打开关闭动画**/
.hide-aside-enter-active,
.hide-aside-leave-active {
  transition: width 0.5s ease;
  width: 210px;
}

.hide-aside-enter-from,
.hide-aside-leave-to {
  width: 0;
}
</style>
